<template>
  <div class="service-areas-container">
    <!-- 服务区域概览 -->
    <el-card shadow="hover" class="overview-card">
      <template #header>
        <div class="card-header">
          <span>服务区域概览</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加服务区域
          </el-button>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ serviceAreas.length }}</div>
            <div class="stat-label">服务区域数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ enabledAreasCount }}</div>
            <div class="stat-label">已启用区域</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ maxDeliveryDistance }}km</div>
            <div class="stat-label">最大配送距离</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">¥{{ averageDeliveryFee }}</div>
            <div class="stat-label">平均配送费</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 服务区域列表 -->
    <el-card shadow="hover" class="areas-list-card">
      <template #header>
        <div class="card-header">
          <span>服务区域管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索区域名称"
              style="width: 200px; margin-right: 10px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px; margin-right: 10px">
              <el-option label="全部" value="" />
              <el-option label="已启用" value="enabled" />
              <el-option label="已禁用" value="disabled" />
            </el-select>
            <el-button @click="refreshAreas">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="filteredAreas" v-loading="loading" stripe>
        <el-table-column prop="name" label="区域名称" min-width="150" />
        <el-table-column prop="province" label="省份" width="100" />
        <el-table-column prop="city" label="城市" width="100" />
        <el-table-column prop="district" label="区县" width="100" />
        <el-table-column prop="maxDistance" label="最大配送距离" width="120">
          <template #default="{ row }">
            {{ row.maxDistance }}km
          </template>
        </el-table-column>
        <el-table-column prop="deliveryFee" label="配送费" width="100">
          <template #default="{ row }">
            ¥{{ row.deliveryFee }}
          </template>
        </el-table-column>
        <el-table-column prop="freeDeliveryAmount" label="免配送费金额" width="130">
          <template #default="{ row }">
            ¥{{ row.freeDeliveryAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="toggleAreaStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="editArea(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="deleteArea(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑服务区域对话框 -->
    <el-dialog
      v-model="areaDialog.visible"
      :title="areaDialog.isEdit ? '编辑服务区域' : '添加服务区域'"
      width="600px"
    >
      <el-form
        :model="areaDialog.form"
        :rules="areaRules"
        ref="areaFormRef"
        label-width="120px"
      >
        <el-form-item label="区域名称" prop="name">
          <el-input
            v-model="areaDialog.form.name"
            placeholder="请输入区域名称"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省份" prop="province">
              <el-select
                v-model="areaDialog.form.province"
                placeholder="请选择省份"
                style="width: 100%"
                @change="onProvinceChange"
              >
                <el-option
                  v-for="province in provinces"
                  :key="province.code"
                  :label="province.name"
                  :value="province.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市" prop="city">
              <el-select
                v-model="areaDialog.form.city"
                placeholder="请选择城市"
                style="width: 100%"
                @change="onCityChange"
              >
                <el-option
                  v-for="city in cities"
                  :key="city.code"
                  :label="city.name"
                  :value="city.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区县" prop="district">
              <el-select
                v-model="areaDialog.form.district"
                placeholder="请选择区县"
                style="width: 100%"
              >
                <el-option
                  v-for="district in districts"
                  :key="district.code"
                  :label="district.name"
                  :value="district.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大配送距离" prop="maxDistance">
              <el-input
                v-model="areaDialog.form.maxDistance"
                type="number"
                :min="1"
                :max="50"
                placeholder="请输入最大配送距离"
              >
                <template #suffix>km</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送费" prop="deliveryFee">
              <el-input
                v-model="areaDialog.form.deliveryFee"
                type="number"
                :min="0"
                placeholder="请输入配送费"
              >
                <template #suffix>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="免配送费金额" prop="freeDeliveryAmount">
          <el-input
            v-model="areaDialog.form.freeDeliveryAmount"
            type="number"
            :min="0"
            placeholder="请输入免配送费的最低订单金额"
          >
            <template #suffix>元</template>
          </el-input>
          <div class="form-tip">
            订单金额达到此金额时免收配送费
          </div>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="areaDialog.form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="areaDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveArea" :loading="saving">
            {{ areaDialog.isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh
} from '@element-plus/icons-vue'

// 服务区域列表
const serviceAreas = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const filterStatus = ref('')

// 省市区数据
const provinces = ref([
  { code: '110000', name: '北京市' },
  { code: '120000', name: '天津市' },
  { code: '310000', name: '上海市' },
  { code: '500000', name: '重庆市' },
  { code: '130000', name: '河北省' },
  { code: '140000', name: '山西省' },
  { code: '210000', name: '辽宁省' },
  { code: '220000', name: '吉林省' },
  { code: '230000', name: '黑龙江省' },
  { code: '320000', name: '江苏省' },
  { code: '330000', name: '浙江省' },
  { code: '340000', name: '安徽省' },
  { code: '350000', name: '福建省' },
  { code: '360000', name: '江西省' },
  { code: '370000', name: '山东省' },
  { code: '410000', name: '河南省' },
  { code: '420000', name: '湖北省' },
  { code: '430000', name: '湖南省' },
  { code: '440000', name: '广东省' },
  { code: '450000', name: '广西壮族自治区' },
  { code: '460000', name: '海南省' },
  { code: '510000', name: '四川省' },
  { code: '520000', name: '贵州省' },
  { code: '530000', name: '云南省' },
  { code: '540000', name: '西藏自治区' },
  { code: '610000', name: '陕西省' },
  { code: '620000', name: '甘肃省' },
  { code: '630000', name: '青海省' },
  { code: '640000', name: '宁夏回族自治区' },
  { code: '650000', name: '新疆维吾尔自治区' }
])

const cities = ref([])
const districts = ref([])

// 对话框
const areaDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: null,
    name: '',
    province: '',
    city: '',
    district: '',
    maxDistance: '',
    deliveryFee: '',
    freeDeliveryAmount: '',
    remark: ''
  }
})

const areaFormRef = ref(null)
const saving = ref(false)

// 表单验证规则
const areaRules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  district: [
    { required: true, message: '请选择区县', trigger: 'change' }
  ],
  maxDistance: [
    { required: true, message: '请输入最大配送距离', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value < 1 || value > 50) {
          callback(new Error('配送距离应在1-50km之间'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  deliveryFee: [
    { required: true, message: '请输入配送费', trigger: 'blur' }
  ],
  freeDeliveryAmount: [
    { required: true, message: '请输入免配送费金额', trigger: 'blur' }
  ]
}

// 计算属性
const filteredAreas = computed(() => {
  let areas = serviceAreas.value
  
  if (searchKeyword.value) {
    areas = areas.filter(area => 
      area.name.includes(searchKeyword.value) ||
      area.province.includes(searchKeyword.value) ||
      area.city.includes(searchKeyword.value) ||
      area.district.includes(searchKeyword.value)
    )
  }
  
  if (filterStatus.value) {
    areas = areas.filter(area => area.status === filterStatus.value)
  }
  
  return areas
})

const enabledAreasCount = computed(() => {
  return serviceAreas.value.filter(area => area.status === 'enabled').length
})

const maxDeliveryDistance = computed(() => {
  if (serviceAreas.value.length === 0) return 0
  return Math.max(...serviceAreas.value.map(area => area.maxDistance))
})

const averageDeliveryFee = computed(() => {
  if (serviceAreas.value.length === 0) return 0
  const total = serviceAreas.value.reduce((sum, area) => sum + area.deliveryFee, 0)
  return (total / serviceAreas.value.length).toFixed(2)
})

// 省份变化
const onProvinceChange = (province) => {
  areaDialog.form.city = ''
  areaDialog.form.district = ''
  
  // 这里应该根据省份获取城市列表
  // 模拟数据
  cities.value = [
    { code: '110100', name: '北京市' },
    { code: '110200', name: '县' }
  ]
  districts.value = []
}

// 城市变化
const onCityChange = (city) => {
  areaDialog.form.district = ''
  
  // 这里应该根据城市获取区县列表
  // 模拟数据
  districts.value = [
    { code: '110101', name: '东城区' },
    { code: '110102', name: '西城区' },
    { code: '110105', name: '朝阳区' },
    { code: '110106', name: '丰台区' },
    { code: '110107', name: '石景山区' },
    { code: '110108', name: '海淀区' }
  ]
}

// 显示添加对话框
const showAddDialog = () => {
  areaDialog.isEdit = false
  areaDialog.visible = true
  resetForm()
}

// 编辑区域
const editArea = (area) => {
  areaDialog.isEdit = true
  areaDialog.visible = true
  
  Object.assign(areaDialog.form, {
    id: area.id,
    name: area.name,
    province: area.province,
    city: area.city,
    district: area.district,
    maxDistance: area.maxDistance,
    deliveryFee: area.deliveryFee,
    freeDeliveryAmount: area.freeDeliveryAmount,
    remark: area.remark || ''
  })
  
  // 加载对应的城市和区县数据
  onProvinceChange(area.province)
  onCityChange(area.city)
}

// 保存区域
const saveArea = async () => {
  try {
    await areaFormRef.value.validate()
    
    saving.value = true
    
    // 这里调用保存API
    // if (areaDialog.isEdit) {
    //   await updateServiceArea(areaDialog.form)
    // } else {
    //   await createServiceArea(areaDialog.form)
    // }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(areaDialog.isEdit ? '服务区域更新成功' : '服务区域添加成功')
    areaDialog.visible = false
    getServiceAreas()
    
  } catch (error) {
    console.error('保存服务区域失败:', error)
    ElMessage.error(error.message || '保存服务区域失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  areaFormRef.value?.resetFields()
  Object.assign(areaDialog.form, {
    id: null,
    name: '',
    province: '',
    city: '',
    district: '',
    maxDistance: '',
    deliveryFee: '',
    freeDeliveryAmount: '',
    remark: ''
  })
  cities.value = []
  districts.value = []
}

// 切换区域状态
const toggleAreaStatus = async (area) => {
  try {
    // 这里调用切换状态API
    // await toggleServiceAreaStatus(area.id, area.status)
    
    ElMessage.success(`服务区域已${area.status === 'enabled' ? '启用' : '禁用'}`)
    
  } catch (error) {
    // 恢复原状态
    area.status = area.status === 'enabled' ? 'disabled' : 'enabled'
    console.error('切换状态失败:', error)
    ElMessage.error('切换状态失败')
  }
}

// 删除区域
const deleteArea = async (area) => {
  try {
    await ElMessageBox.confirm(
      `确认删除服务区域"${area.name}"？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用删除API
    // await deleteServiceArea(area.id)
    
    ElMessage.success('服务区域删除成功')
    getServiceAreas()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务区域失败:', error)
      ElMessage.error('删除服务区域失败')
    }
  }
}

// 获取服务区域列表
const getServiceAreas = async () => {
  loading.value = true
  try {
    // 这里调用获取服务区域API
    // const response = await getServiceAreasList()
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    serviceAreas.value = []
    
  } catch (error) {
    console.error('获取服务区域失败:', error)
    ElMessage.error('获取服务区域失败')
  } finally {
    loading.value = false
  }
}

// 刷新区域列表
const refreshAreas = () => {
  getServiceAreas()
}

onMounted(() => {
  getServiceAreas()
})
</script>

<style scoped>
.service-areas-container {
  padding: 20px;
}

.overview-card,
.areas-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  margin-bottom: 0;
}

:deep(.el-switch) {
  --el-switch-on-color: #67C23A;
  --el-switch-off-color: #DCDFE6;
}
</style>
